package cn.vin.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Wu Shenzhuang
 * @Date: 2019/5/31 11:17
 */
public class DogFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(DogFilter.class);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
            chain.doFilter(request, response);
            return;
        }
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String path = req.getRequestURI();
        long start = System.currentTimeMillis();
        try{
            chain.doFilter(req, res);
        } catch (Exception e) {
            logger.error("dog monitor 请求报错,url:{},error:{}",path,e.getMessage());
            throw e;
        }
        long end = System.currentTimeMillis();
        long consumTime = end - start;
        if(consumTime <= 300) {
            logger.info("dog monitor 请求正常,url:{},耗时:{}",path,consumTime);
        } else if(consumTime > 3000) {
            logger.error("dog monitor 请求时间过长,url:{},耗时:{}",path,consumTime);
        } else {
            logger.warn("dog monitor 请求时间超过阈值,url:{},耗时:{}",path,consumTime);
        }
    }

    @Override
    public void destroy() {

    }
}
